package controller;

import constant.Constant;
import entity.User;
import exception.DuplicateUsernameException;
import exception.UserDisabledException;
import exception.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.UserService;
import vo.AjaxResult;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/show/{viewName}")
    public String show(@PathVariable("viewName") String viewName){
        return viewName;
    }

    @ExceptionHandler(DuplicateUsernameException.class)
    public ModelAndView registExceptionHandler(Exception e){
        return new ModelAndView("regist","message",e.getMessage());
    }

    @ExceptionHandler({UserNotFoundException.class, UserDisabledException.class})
    public ModelAndView loginExceptionHandler(Exception e){
        return new ModelAndView("login","message",e.getMessage());
    }

    @RequestMapping("/regist")
    public String regist(User user)throws Exception{
        userService.regist(user);
        return "redirect:/user/showLogin";
    }

    @RequestMapping("/login")
    public String login(String username, String password, HttpSession session)throws Exception{
        User user=userService.login(username,password);
        session.setAttribute(Constant.UserAuthorization.SESSION_AUTHORIZATION_PARAM,user);
        return "redirect:/user/show/success";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/user/showLogin";
    }

    @RequestMapping("/validateUsername")
    public @ResponseBody AjaxResult validateUsername(String username){
        try {
            userService.validateUsername(username);
            return AjaxResult.success("用户名可用");
        } catch (DuplicateUsernameException e) {
            return new AjaxResult(Constant.AjaxCode.AJAX_CODE_EXCEPTION,e.getMessage(),null);
        }
    }















}
